package org.adit.spring.hibernate.dao;

import java.util.List;

import org.adit.spring.hibernate.entity.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.Component;

@Component
public class MapDao {

	private final Session session; 
	
	public MapDao(Session session){
		this.session = session;
	}
	
	public void salva(Map map) {
		Transaction tx = session.beginTransaction();
		session.save(map);
		tx.commit();
	}
	
	@SuppressWarnings("unchecked")
	public List<Map> listaTudo(){
		return this.session.createCriteria(Map.class).list();
	}
	
	public Map carrega(Long id) {
		return (Map) this.session.load(Map.class, id);
	}
	
	public void atualiza(Map map) {
		Transaction tx = session.beginTransaction();
		session.update(map);
		tx.commit();
	}
	
	public void remove(Map map) {
		Transaction tx = session.beginTransaction();
		this.session.delete(map);
		tx.commit();
	}

	@SuppressWarnings("unchecked")
	public List<Map> busca(String nome) {
		return session.createCriteria(Map.class)
			.add(Restrictions.ilike("nome", nome, MatchMode.ANYWHERE))
			.list();
	}

	public void recarrega(Map map) {
		session.refresh(map);	
	}
}